from google.appengine.api.urlfetch import fetch
from google.appengine.api import memcache 
from datetime import datetime
import re
import time
from xml.dom.minidom import parseString

mta_status_url = 'http://www.mta.info/status/serviceStatus.txt'
alternate_parking_url = "http://www.nyc.gov/html/dot/downloads/excel/altside2010.csv"
fname = 'mtaalerts~.txt'

def load_alerts():

	resp = fetch(mta_status_url)
	text = resp.content

	dom = parseString(text)
	subway = dom.getElementsByTagName("subway")[0]
	lines = subway.getElementsByTagName("line")
	s = ''
	alerts = ''
	for line in lines:
		name = line.getElementsByTagName("name")[0].firstChild.nodeValue
		status = line.getElementsByTagName("status")[0].firstChild.nodeValue
		text = ''
		textNode = line.getElementsByTagName("text")[0]
		if textNode != None and textNode.firstChild != None:
			text = textNode.firstChild.nodeValue
		
		if status != 'GOOD SERVICE':
			status = '<b><font color="red">' + status.strip() + '</font></b>'
			alerts = alerts + name.strip() + ' '
	
		s += name + ':' + status + '<br>' + text.replace('<br />', '\n').strip() + '=============<br>\n'

	if len(alerts) == 0:
		alerts = 'OK'
		
	memcache.set('mta_alert', alerts, 1200)
	memcache.set('mta_alert_fetchtime', time.time(), 1200)
	return s

def get_last_alert():
	fetchtime = memcache.get('mta_alert_fetchtime')
	if fetchtime is None:
		load_alerts()

	fetchtime = memcache.get('mta_alert_fetchtime')
	s = memcache.get('mta_alert') + ' (' + str(int(time.time() - fetchtime) / 60) + ')'
	return s
	
def parking(req):
	
	fullParking = req.startswith('/park/full')
	fname = 'altside~.txt'
	cache.download(mta.alternate_parking_url, fname, 720)
	s = cache.get(fname)

	today = datetime.today()
	lines = s.split('\n')
	lines.pop(0)
	p = 0
	s = ""
	for line in lines:
		cols = line.split(',')
		if len(cols) < 7:
			continue
		dd = datetime.strptime(cols[1], "%m/%d/%Y")
		d = dd - today
		if p == 0 and d.days >= 0:
			p = 1
		if p > 0:
			if dd.weekday() == 0 or dd.weekday() == 2 or dd.weekday() == 3 or dd.weekday() == 4:
				s += fg(datetime.strftime(dd, "%a %m/%d "), 'green')
				if fullParking == True:
					s += fg(cols[6], 'green') + "\n"
			else:
				s += datetime.strftime(dd, "%a %m/%d ")
				if fullParking == True:
					s += cols[6] + "\n"
			p += 1
		if p > 4:
			break
	
	h = ''
	if fullParking == True:
		h +=  '--- ' + fg('P', 'cyan') + 'arking ---\n'
	else:
		h += '+-- ' + fg('P', 'cyan') + 'arking: '

	s = h + s
	print('===='+s+'=======')
	return s
